/**
 * Created by guillaume on 16/01/14.
 */
/* Gridster for widgets */
gridster = {};

function loadGridster(id) {
    if (!(id in gridster)){
        var elem = $("#" + id + " .gridster");
        gridster[id] = elem.gridster({
            namespace: "#" + id,
            widget_margins: [10, 10],
            widget_base_dimensions: [150, 150],
            serialize_params: function ($w, wgd) {
                return { col: wgd.col, row: wgd.row, size_x: wgd.size_x, size_y: wgd.size_y, id_widget: $w.data('id_widget') }
            },
            resize: {
                enabled: true,
                max_size: [3, 3],
                stop: function(e, ui, $widget) {
                    updateGrid(id, JSON.stringify(gridster[id].serialize()));
                }
            },
            draggable: {
                stop: function(e, ui, $widget) {
                    updateGrid(id, JSON.stringify(gridster[id].serialize()));
                }
            }
        }).data('gridster');
        if(!elem.closest('.page').data('admin') && gridster[id] != null)
            gridster[id].disable().disable_resize();
    }
    $('.page.active').css('visibility', 'visible');
}

function updateGrid(id, grid){
    var page_id = $('#'+id).data('id');
    $.post(
        '/AdminPages/changeGrid/'+page_id,
        {grid: grid},
        function(data){
            notify('top-right', 'Page grid updated', 'info', 2000);
        }
    )
}

$(document).ajaxComplete(function(e, r, a){
    if(a.url.indexOf('/page/') != -1){
        window.setTimeout(function(){
            loadGridster($('.page.active')[0].id);
        }, 1000);
    }
})

/* End Gridster */